/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.baseDataView;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Date;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.bean.TOpLog;
import com.ruipengkj.bean.TProductCatalog;
import com.ruipengkj.bean.TStockAlarm;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.MatcherFormatUtil;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JLabelJTextAreaComponent;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.component.jtree.OverwriteDefaultMutableTreeNode;
import com.ruipengkj.component.tabbedPane.PerTabbedPaneUI;
import com.ruipengkj.component.tabbedPane.RPTabHeadComponent;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TStockAlarmService;

public class DataCommodityAddOrModifyDialog extends IDialog implements CaretListener {

	private static final long serialVersionUID = 1L;
	
	private JLabelJTextFieldComponent CommodityID;//商品编号
	private JLabelJTextFieldComponent Price;//价格
	private JLabelJTextAreaComponent Des;//商品描述
	private JLabelJTextFieldComponent Name;//商品名称
	private JLabelJTextFieldComponent Point;//附送积分
	private JLabelJComboBoxComponent DiscountType;//打折类型
	private JLabelJTextFieldComponent DisCount;//折扣率DECIMAL(20,3)
	private JLabelJTextFieldComponent DiscountPrice;//现价
	private JLabelJTextAreaComponent Detail;//商品详细信息TEXT
	private JLabelJComboBoxComponent Type;//类型TINYINT 1为正常商品 2为套餐
	private JLabelJComboBoxComponent Status;//状态TINYINT 1为已发布 2为未发布
	private JLabelJTextFieldComponent Barcode;//条形码
	private JLabelJTextFieldComponent BatchPrice;//批发价
	private JLabelJComboBoxComponent Unit;
	private JLabelJTextFieldComponent MadePlace;//产地
	private JLabelJTextFieldComponent Color;//颜色VARCHAR(10)
	private	JLabelJTextFieldComponent Batch;//批次VARCHAR(16)
	private JLabelJTextFieldComponent Std;//产品规格
	private JLabelJTextFieldComponent TProductCatalog;//商品目录
	private JLabelJComboBoxComponent intoSales;//进销属性-0-进货销售，1-仅进货，2-仅销售
	
	private JLabelJTextFieldComponent WeightingPrice;//加权价
	private TCommodityService tCommodityService; 
	private DataTProductCatalogSelectDialog dataTProductCatalogSelectDialog;//选择商品目录面板
	private OverwriteDefaultMutableTreeNode treeNode;//父级目录节点
	private JButton yesButton; //确定按钮
	private JButton noButton; //取消按钮
	
	private JLabelJTextFieldComponent minStock;//库存上阀值
	private JLabelJTextFieldComponent maxStock;//库存下阀值
	
	public boolean isSuccess=false;
	private TCommodity tCommodity=null;
	
	private TStockAlarmService tStockAlarmService = BuildSpringApplication.getInstance().getTStockAlarmServiceImpl();
	
	private boolean isNew = true;
	
	private JTabbedPane tabbedPane = new JTabbedPane() {
		private static final long serialVersionUID = 1L;
		private Color color1 = new Color(246, 163, 49);
		@Override
		public void paint(Graphics g) {
			super.paint(g);
//			g.setColor(color2);
//			g.drawLine(0, 100, this.getWidth(), 100);
			g.setColor(color1);
			g.fillRect(0, 0, 4, this.getHeight());
			g.fillRect(this.getWidth()-4, 0, 4, this.getHeight());
		};
	};
	private JPanel onePanel = createBoxJPanel(BoxLayout.Y_AXIS, true);//JTabbedPane的第一个面板：基本信息
	private JPanel twoPanel = createBoxJPanel(BoxLayout.Y_AXIS, false);//JTabbedPane的第二个面板:额外信息
	private DataCommodityPicturePanel threePanel = new DataCommodityPicturePanel();//第3个面板 --图片
	private DataCommodityPackagePanel fourPanel = null;//JTabbedPane的第二个面板:套餐信息
	
	public DataCommodityAddOrModifyDialog(JDialog jd, String title, boolean b) {
		super(jd, title, b);
		this.initViews();
		this.initListener();
		this.setSize(900, 500);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				if (Util.showConfirmDialog("是否退出软件？") == 0) {
					System.exit(0);
				}
			}
		});
	}
	
	
	private void initViews() {
		tCommodityService=BuildSpringApplication.getInstance().getTCommodityServiceImpl();
		JPanel main_panel = uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
		main_panel.setOpaque(true);
		main_panel.setBackground(Util.PANEL_COLOR);
		
		CommodityID = new JLabelJTextFieldComponent(" 商品编号：", 30);//商品编号
		CommodityID.getText().setEditable(false);
		CommodityID.getText().setText(UUID.GenUUID15());
		Name = new JLabelJTextFieldComponent("*", " 商品名称：", 30);//商品名称
		Price = new JLabelJTextFieldComponent("*", "销售价格：", 30);//价格
		
		DiscountType = new JLabelJComboBoxComponent("  打折类型：",ApplicationContext.DISCOUNTTYPE_TYPE_MAP() ,188);//打折类型
		DisCount = new JLabelJTextFieldComponent("*", "折 扣 率：", 30);//折扣率DECIMAL(20,3)
		DiscountPrice = new JLabelJTextFieldComponent("*", "现    价：", 30);//现价
		DiscountPrice.getText().setEditable(false);
		DisCount.getText().setEditable(false);
		DisCount.getText().setText("1.0");
		DiscountPrice.getText().setText("0.0");
		
		Type = new JLabelJComboBoxComponent("  类    型：",ApplicationContext.COMMODITY_TYPE_MAP() ,188);//类型TINYINT 1为正常商品 2为套餐
		Status = new JLabelJComboBoxComponent("  状    态：",ApplicationContext.COMMODITY_STATUS_MAP() ,188);//状态TINYINT 1为已发布 2为未发布
		BatchPrice = new JLabelJTextFieldComponent("*", "批 发 价：", 30);;//批发价
		
		Point= new JLabelJTextFieldComponent("  附送积分：", 30);;//附送积分
		Unit = new JLabelJComboBoxComponent("  计量单位：", ApplicationContext.UNIT_MAP(), 188);
		Unit.getBox().setEditable(true);
		MadePlace= new JLabelJTextFieldComponent(" 产    地：", 30);//产    地
		
		Color= new JLabelJTextFieldComponent("  颜    色：", 30);//颜色
		Batch= new JLabelJTextFieldComponent("  批    次：", 30);//批    次
		TProductCatalog = new JLabelJTextFieldComponent("*", "商品目录：",30);;//商品目录
	
		
		Std = new JLabelJTextFieldComponent("  产品规格：", 30);;//产品规格
		WeightingPrice = new JLabelJTextFieldComponent("加  权  价：", 30);//加权价
		WeightingPrice.getText().setEditable(false);
		
		Des = new JLabelJTextAreaComponent(" 商品描述：", 60,4);;//商品描述
		Detail = new JLabelJTextAreaComponent(" 详细信息：", 60,4);//商品详细信息TEXT
		Barcode = new JLabelJTextFieldComponent(" 条 形 码：", 30);//条 形 码
		
		JPanel jp1=uiFactory.createFlowJPanel(FlowLayout.LEFT, Util.PANEL_COLOR);
		jp1.add(CommodityID);//商品ID
		jp1.add(Name);//商品名称
		jp1.add(TProductCatalog);//商品分类
		JPanel jp1_1 = uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
		jp1_1.add(jp1);
		jp1_1.setBorder(uiFactory.createTitledBorder("基础信息:"));
		
		JPanel jp2=uiFactory.createFlowJPanel(FlowLayout.LEFT, Util.PANEL_COLOR);
		jp2.add(Price);//商品价格
		jp2.add(BatchPrice);//批发价
		jp2.add(WeightingPrice);//加权价
		
		JPanel jp3=uiFactory.createFlowJPanel(FlowLayout.LEFT, Util.PANEL_COLOR);
		jp3.add(DiscountType);//打折类型
		jp3.add(DisCount);//折扣率
		jp3.add(DiscountPrice);//现价
		JPanel jp2_2 = uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
		jp2_2.add(jp2);
		jp2_2.add(jp3);
//		jp2_2.setBorder(BorderFactory.createTitledBorder("价格"));
		jp2_2.setBorder(uiFactory.createTitledBorder("价格:"));
		
		JPanel jp4=uiFactory.createBoxJPanel(BoxLayout.Y_AXIS );
		jp4.add(Type);//商品类型
		jp4.add(Point);//附送积分
		jp4.add(Unit);//计量单位
		
		JPanel jp5=uiFactory.createBoxJPanel(BoxLayout.Y_AXIS );
		jp5.add(MadePlace);//产地
		jp5.add(Color);//颜色
		jp5.add(Batch);//批次
		
		
		JPanel jp6=uiFactory.createBoxJPanel(BoxLayout.Y_AXIS );
		
		intoSales = new JLabelJComboBoxComponent(" 进销类型：", ApplicationContext.INFO_SALES, 188);
		
		jp6.add(intoSales);
		
		jp6.add(Barcode);//条码
		jp6.add(Std);//产品规格
		
		JPanel jp3_3 = uiFactory.createBoxJPanel(BoxLayout.X_AXIS);
		jp3_3.add(jp4);
		jp3_3.add(jp5);
		jp3_3.add(jp6);
//		jp3_3.setBorder(BorderFactory.createTitledBorder("其它信息"));
		jp3_3.setBorder(uiFactory.createTitledBorder("其它信息:"));
		
		minStock = new JLabelJTextFieldComponent(" 最低阀值：", 30);//库存上阀值
		maxStock = new JLabelJTextFieldComponent("最高阀值：", 30);//库存下阀值
		JPanel jp7 = uiFactory.createFlowJPanel(FlowLayout.LEFT, Util.PANEL_COLOR);
		jp7.add(minStock);
		jp7.add(maxStock);
		JPanel jp4_4 = uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
		jp4_4.add(jp7);
		jp4_4.setBorder(uiFactory.createTitledBorder("库存阀值:"));
		
		JPanel jp8=uiFactory.createFlowJPanel(FlowLayout.LEFT, Util.PANEL_COLOR);
		jp8.add(Status);//发布状态
		
		JPanel jp9 = uiFactory.createFlowJPanel(FlowLayout.LEFT, Util.PANEL_COLOR);
		jp9.add(Des);//说明
		
		JPanel jp10 = uiFactory.createFlowJPanel(FlowLayout.LEFT, Util.PANEL_COLOR);
		jp10.add(Detail);//详细说明
		
		JPanel jp5_5 = uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
		jp5_5.add(jp8);
		jp5_5.add(jp9);
		jp5_5.add(jp10);
		jp5_5.setBorder(uiFactory.createTitledBorder("发布:"));
		
		JPanel jp100 = new BorderJPanel(ImageFactory.loadImage(ImageFactory.DIALOG_DOWN_BG_1).getImage());
		yesButton = new RPJButtonWhite("保存(Ctrl+S)");
		noButton = new RPJButtonWhite("取消(Ctrl+Q)");
		jp100.add(yesButton);
		jp100.add(noButton);
		jp100.setBackground(new Color(255, 255, 255));

		onePanel.add(jp1_1);
		onePanel.add(jp2_2);
		onePanel.add(jp3_3);
		twoPanel.add(jp4_4);
		twoPanel.add(jp5_5);
	
		tabbedPane.setOpaque(true);
		tabbedPane.setBackground(new Color(255, 255, 255));
		tabbedPane.add(onePanel, "基本数据");
		tabbedPane.add(twoPanel, "额外数据");
		tabbedPane.add(threePanel, "图片数据");
		tabbedPane.setCursor(Util.CURSOR_DEFAULT);
		
		tabbedPane.setUI(new PerTabbedPaneUI(tabbedPane, 31));
		tabbedPane.setTabComponentAt(0, new RPTabHeadComponent(tabbedPane, "基本数据"));
		tabbedPane.setTabComponentAt(1, new RPTabHeadComponent(tabbedPane, "额外数据"));
		tabbedPane.setTabComponentAt(2, new RPTabHeadComponent(tabbedPane, "图片数据"));
		
		this.setIContentPane(tabbedPane);
		this.add(jp100, BorderLayout.SOUTH);
	}
	
	private void initListener(){
		yesButton.addActionListener(this);
		yesButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		noButton.addActionListener(this);
		noButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		TProductCatalog.getText().addKeyListener(this);
		TProductCatalog.getText().addMouseListener(this);
		DiscountType.getBox().addActionListener(this);
		Price.getText().addCaretListener(this);
		DisCount.getText().addCaretListener(this);
		Type.getBox().addActionListener(this);
	}
	
	private JPanel createBoxJPanel(int type, final boolean isOne){
		JPanel p=new JPanel() {
			private static final long serialVersionUID = 1L;
			private Color color = new Color(225, 225, 225);
			@Override
			public void paint(Graphics g) {
				g.setColor(color);
				g.drawLine(0, 75, this.getWidth()-1, 75);
				if (isOne)
					g.drawLine(0, 211, this.getWidth()-1, 211);
				super.paint(g);
			}
		};
		p.setOpaque(false);
		BoxLayout boxLayout=new BoxLayout(p, type);
		p.setLayout(boxLayout);
		return p;
	}
		
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == yesButton) {
//			String CommodityIDStr=CommodityID.getText().getText().trim();//商品编号
			String PriceStr=Price.getText().getText().trim();//价格
			String DesStr=Des.getArea().getText().trim();//商品描述
			String NameStr=Name.getText().getText().trim();//商品名称
			String PointStr=Point.getText().getText().trim();//附送积分
			String DiscountTypeStr=DiscountType.getBox().getSelectedItem().toString();//打折类型
			String DisCountStr=DisCount.getText().getText().trim();//折扣率DECIMAL(20,3)
			String DiscountPriceStr=DiscountPrice.getText().getText().trim();//现价
			String DetailStr=Detail.getArea().getText().trim();//商品详细信息TEXT
			String TypeStr=Type.getBox().getSelectedItem().toString();//类型TINYINT 1为正常商品 2为套餐
			String StatusStr=Status.getBox().getSelectedItem().toString();//状态TINYINT 1为已发布 2为未发布
			String BarcodeStr=Barcode.getText().getText().trim();//条形码
			String BatchPriceStr=BatchPrice.getText().getText().trim();//批发价
			String UnitStr=Unit.getBox().getSelectedItem().toString().trim();//商品计量单位
			String MadePlaceStr=MadePlace.getText().getText().trim();//产地
			String ColorStr=Color.getText().getText().trim();//颜色VARCHAR(10)
			String BatchStr=Batch.getText().getText().trim();//批次VARCHAR(16)
			String StdStr= Std.getText().getText().trim();//产品规格
			String TProductCatalogStr=TProductCatalog.getText().getText().trim();//商品目录

			//价格
			if(!MatcherFormatUtil.MatcherPriceScheme(PriceStr)){
				JOptionPane.showMessageDialog(null, "价格格式不正确，且小数点左边不能大于10位，右边不能大于2位");
				Price.getText().requestFocus();
				return;
			}
			//描述
			if(DesStr.length()>512){
				JOptionPane.showMessageDialog(null, "描述不能大于512个字");
				Des.getArea().requestFocus();
				return;
			}
			//名称
			if(NameStr.equals("")||NameStr.length()>256){
				JOptionPane.showMessageDialog(null, "商品名称不能为空，且不能大于256个字");
				Name.getText().requestFocus();
				return;
			}
			//附送积分
			if (!PointStr.equals(""))
			if(!MatcherFormatUtil.MatcherNumberScheme(PointStr)||PointStr.length()>5){
				JOptionPane.showMessageDialog(null, "附送积分格式不正确，且不能大于5位");
				Point.getText().requestFocus();
				return;
			}
			String minStockStr = minStock.getText().getText();
			//库存下阀值
			if (!minStockStr.equals(""))
			if(!MatcherFormatUtil.MatcherNumberScheme(minStockStr)||minStockStr.length()>5){
				JOptionPane.showMessageDialog(null, "库存下阀值不正确，且不能大于5位");
				minStock.getText().requestFocus();
				return;
			}
			String maxStockStr = maxStock.getText().getText();
			//库存上阀值
			if (!maxStockStr.equals(""))
			if(!MatcherFormatUtil.MatcherNumberScheme(maxStockStr)||maxStockStr.length()>8){
				JOptionPane.showMessageDialog(null, "库存上阀值不正确，且不能大于8位");
				maxStock.getText().requestFocus();
				return;
			}
			//折扣率
			if(!MatcherFormatUtil.MatcherPriceScheme(DisCountStr)){
				JOptionPane.showMessageDialog(null, "折扣率格式不正确，且小数点左边不能大于10位，右边不能大于2位");
				DisCount.getText().requestFocus();
				return;
			}
			//现价
			if(!MatcherFormatUtil.MatcherPriceScheme(DiscountPriceStr)){
				JOptionPane.showMessageDialog(null, "现价不正确，且小数点左边不能大于10位，右边不能大于2位");
				DiscountPrice.getText().requestFocus();
				return;
			}
			//详细信息
			if(DetailStr.length()>65535){
				JOptionPane.showMessageDialog(null, "详细信息不能大于65535个字");
				Detail.getArea().requestFocus();
				return;
			}
			//条形码
			if(BarcodeStr.length()>20){
				JOptionPane.showMessageDialog(null, "条形码不能大于20个字");
				Barcode.getText().requestFocus();
				return;
			}
			//批发价
			if(!MatcherFormatUtil.MatcherPriceScheme(BatchPriceStr)){
				JOptionPane.showMessageDialog(null, "批发价不正确，且小数点左边不能大于10位，右边不能大于2位");
				BatchPrice.getText().requestFocus();
				return;
			}
			//产地
			if(MadePlaceStr.length()>32){
				JOptionPane.showMessageDialog(null, "产地不能大于32个字");
				MadePlace.getText().requestFocus();
				return;
			}
			//颜色
			if(ColorStr.length()>10){
				JOptionPane.showMessageDialog(null, "颜色不能大于10个字");
				Color.getText().requestFocus();
				return;
			}
			//批次
			if(BatchStr.length()>16){
				JOptionPane.showMessageDialog(null, "批次不能大于16个字");
				Batch.getText().requestFocus();
				return;
			}
			
			//产品规格
			if(StdStr.length()>64){
				JOptionPane.showMessageDialog(null, "产品规格不能大于64个字");
				Std.getText().requestFocus();
				return;
			}
			if(TProductCatalogStr.equals("")){
				JOptionPane.showMessageDialog(null, "请选择商品目录");
				return;
			}
			if (Type.getBox().getSelectedIndex() == 1) {
				if (!fourPanel.check()) {
					Util.showMessageDialog("请先为此套餐添加商品！");
					tabbedPane.setSelectedIndex(3);
					return;
				}
			}
			if(treeNode==null||treeNode.getNodeStringID()==null){
				if(tCommodity.getTProductCatalog()==null){
					tCommodity.setTProductCatalog(null);
				}
			}else if(treeNode.getNodeStringID().equals("")){
				tCommodity.setTProductCatalog(null);
			}else{
				tCommodity.setTProductCatalog(new TProductCatalog(treeNode.getNodeStringID()));
			}
//			tCommodity.setCommodityID(CommodityIDStr);//商品编号
			tCommodity.setPrice(Double.parseDouble(PriceStr));//价格
			tCommodity.setDes(DesStr);//商品描述
			tCommodity.setName(NameStr);//商品名称
			if (!PointStr.equals(""))
				tCommodity.setPoint(Integer.parseInt(PointStr));//附送积分
			tCommodity.setDiscountType((Byte)DiscountType.getKeyByVaule(DiscountTypeStr));//打折类型
			tCommodity.setDisCount(Double.parseDouble(DisCountStr));//折扣率DECIMAL(20,3)
			tCommodity.setDiscountPrice(Double.parseDouble(DiscountPriceStr));//现价
			tCommodity.setDetail(DetailStr);//商品详细信息TEXT
			if (tCommodity.getSmallPic() != null && !tCommodity.getSmallPic().equals("")) {
				new File(this.firstImagePath(tCommodity.getSmallPic())).delete();
			}
			tCommodity.setType((Byte)Type.getKeyByVaule(TypeStr));//类型TINYINT 1为正常商品 2为套餐
			tCommodity.setStatus((Byte)Status.getKeyByVaule(StatusStr));//状态TINYINT 1为已发布 2为未发布
			tCommodity.setBarcode(BarcodeStr);//条形码
			tCommodity.setBatchPrice(Double.parseDouble(BatchPriceStr));//批发价
			tCommodity.setUnit(UnitStr);//商品计量单位
			tCommodity.setMadePlace(MadePlaceStr);//产地
			tCommodity.setColor(ColorStr);//颜色VARCHAR(10)
			tCommodity.setBatch(BatchStr);//批次VARCHAR(16)
			tCommodity.setValidityUnit(ApplicationContext.VALIDITY_1);
			tCommodity.setStd(StdStr);//产品规格
			if (intoSales.getBox().getSelectedIndex() != -1) {
				tCommodity.setIntoSales(intoSales.getBox().getSelectedItem().toString());
			}
			try {
				if (isNew) {
					List<TCommodity> list = tCommodityService.findByNameService(NameStr);
					if (list != null && list.size() != 0) {
						if (Util.showConfirmDialog("存在相同名字的商品，确定添加吗？") != 0)
							return;
					}
				}
				tCommodityService.saveOrUpdateService(tCommodity);
				
				if (fourPanel != null)
					fourPanel.save();
				isSuccess=true;
				if(isNew){
					BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("添加商品信息");
				}else{
					BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("修改商品信息");	
				}
				
				TStockAlarm tStockAlarm = findTStockAlarm(tCommodity);
				if (!minStockStr.equals("") || !maxStockStr.equals("")) {
					if (tStockAlarm == null) {
						tStockAlarm = new TStockAlarm(); 
						tStockAlarm.setAlarmID(UUID.GenUUID15());//报警编号CHAR(15)PK
						tStockAlarm.setType("1");//报警类型 1为总量报警  2为任一仓库数量达阀值报警  3为某一仓库数量达阀值报警
						tStockAlarm.setStoreID(null);//仓库编号CHAR(15)
						tStockAlarm.setOperator(ApplicationContext.OPERATOR_ID);//操作人	
						tStockAlarm.setHappenTime(new Date());//操作时间DATETIME
						tStockAlarm.setMinWalve(Integer.parseInt(minStockStr.equals("")?"0":minStockStr));//最低阀值Integer
						tStockAlarm.setMaxWalve(Integer.parseInt(maxStockStr.equals("")?"0":maxStockStr));//最高阀值Integer
						tStockAlarm.setTCommodity(tCommodity);//商品
					} else {
						tStockAlarm.setMinWalve(Integer.parseInt(minStockStr.equals("")?"0":minStockStr));//最低阀值Integer
						tStockAlarm.setMaxWalve(Integer.parseInt(maxStockStr.equals("")?"0":maxStockStr));//最高阀值Integer
					}
					tStockAlarmService.saveOrUpdateService(tStockAlarm);
				} else {
					if (tStockAlarm != null) {
						tStockAlarmService.deleteService(tStockAlarm.getAlarmID());
					}
				}
				
				threePanel.save(tCommodity);
				
				JOptionPane.showMessageDialog(null, "操作成功");
			} catch (Exception e1) {
				e1.printStackTrace();
				JOptionPane.showMessageDialog(null, "操作失败");
				isSuccess=false;
			}
			this.dispose();
		} else if(e.getSource() == noButton) {
			if(Util.showConfirmDialog("是否要取消？")==0){
				isSuccess=false;
				this.dispose();
			}
		} else if (e.getSource() == DiscountType.getBox()) {
			switch (DiscountType.getBox().getSelectedIndex()) {
			case 0:
				DisCount.getText().setEditable(false);
				DisCount.getText().setText("1.0");
				DiscountPrice.getText().setEditable(false);
				break;
			case 1:
				DisCount.getText().setEditable(true);
				DiscountPrice.getText().setEditable(false);
				break;
			case 2:
				DisCount.getText().setText("1.0");
				DisCount.getText().setEditable(false);
				DiscountPrice.getText().setEditable(true);
			}
			Money();
		} else if (e.getSource() == Type.getBox()) {
			if (Type.getBox().getSelectedIndex() == 1) {
				if (tabbedPane.getComponentCount() >= 5)
					return;
				System.out.println(tabbedPane.getComponentCount());
				fourPanel = new DataCommodityPackagePanel();
				fourPanel.showDialog(tCommodity.getCommodityID(), isNew);
				tabbedPane.add(fourPanel, "套餐属性");
				tabbedPane.setTabComponentAt(3, new RPTabHeadComponent(tabbedPane, "套餐属性"));
			} else {
				tabbedPane.remove(fourPanel);
//				tabbedPane.removeTabAt(3);
			}
		}
		super.actionPerformed(e);
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getSource()==TProductCatalog.getText()){
			//选择商品类型
			this.selectProductCatalog();
		}
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		if(e.getSource()==TProductCatalog.getText()){
			//选择商品类型
			this.selectProductCatalog();
		}
	}
	
	private void selectProductCatalog(){
		dataTProductCatalogSelectDialog=new DataTProductCatalogSelectDialog(this, "选择商品类型", true);
		treeNode=dataTProductCatalogSelectDialog.getTreeNode();
		if(treeNode!=null){
			TProductCatalog.getText().setText(treeNode.getNodeName());
		}
	}
	
	public void showDialog(TCommodity tCommodity,OverwriteDefaultMutableTreeNode treeNode){
		this.isSuccess=false;
		if(tCommodity!=null){
			isNew =false;
//			this.WeightingPrice.getText().setText(ApplicationContext.WeightingPrice(tCommodity)+"");
			this.WeightingPrice.getText().setText(tCommodity.getAvgPrice()+"");
			this.tCommodity=tCommodity;
			CommodityID.getText().setText(tCommodity.getCommodityID());//商品编号
			Price.getText().setText(tCommodity.getPrice()+"");//价格
			Des.getArea().setText(tCommodity.getDes());//商品描述
			Name.getText().setText(tCommodity.getName());//商品名称
			Point.getText().setText(tCommodity.getPoint()+"");//附送积分
			DiscountType.getBox().setSelectedItem(ApplicationContext.DISCOUNTTYPE_TYPE_MAP().get(tCommodity.getDiscountType()));//打折类型
			DisCount.getText().setText(tCommodity.getDisCount()+"");//折扣率DECIMAL(20,3)
			DiscountPrice.getText().setText(tCommodity.getDiscountPrice()+"");//现价
			Detail.getArea().setText(tCommodity.getDetail());//商品详细信息TEXT
			Type.getBox().setSelectedItem(ApplicationContext.COMMODITY_TYPE_MAP().get(tCommodity.getType()));//类型TINYINT 1为正常商品 2为套餐
			Status.getBox().setSelectedItem(ApplicationContext.COMMODITY_STATUS_MAP().get(tCommodity.getStatus()));//状态TINYINT 1为已发布 2为未发布
			Barcode.getText().setText(tCommodity.getBarcode());//条形码
			BatchPrice.getText().setText(tCommodity.getBatchPrice()+"");//批发价
			Unit.addElement(tCommodity.getUnit());//商品计量单位
			Unit.getBox().setSelectedItem(tCommodity.getUnit());//商品计量单位
			MadePlace.getText().setText(tCommodity.getMadePlace());//产地
			Color.getText().setText(tCommodity.getColor());//颜色VARCHAR(10)
			Batch.getText().setText(tCommodity.getBatch());//批次VARCHAR(16)
			Std.getText().setText(tCommodity.getStd());//产品规格
			if (tCommodity.getIntoSales() != null) {
				intoSales.getBox().setSelectedItem(tCommodity.getIntoSales());
			}
			if(tCommodity.getTProductCatalog()==null){
				TProductCatalog.getText().setText("所有产品");
			}else{
				TProductCatalog.getText().setText(tCommodity.getTProductCatalog().getName());//商品目录
			}
			
			TStockAlarm tStockAlarm = findTStockAlarm(tCommodity);
			if (tStockAlarm != null) {
				minStock.getText().setText(tStockAlarm.getMinWalve() == 0 ? "":tStockAlarm.getMinWalve()+"");//库存上阀值
				maxStock.getText().setText(tStockAlarm.getMaxWalve() == 0 ? "":tStockAlarm.getMaxWalve()+"");//库存下阀值
			}
		}else{
			this.tCommodity = new TCommodity(UUID.GenUUID15());
			isNew =true;
			this.treeNode=treeNode;
			if(treeNode!=null){
				TProductCatalog.getText().setText(treeNode.getNodeName());
				try {
					TProductCatalog tProductCatalog = BuildSpringApplication.getInstance().getTProductCatalogServiceImpl().getByIdService(treeNode.getNodeStringID());
					if (tProductCatalog != null && tProductCatalog.getIntoSales() != null) {
						this.intoSales.getBox().setSelectedItem(tProductCatalog.getIntoSales());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}
		threePanel.dataShow(this.tCommodity);
		this.setVisible(true);
	}

	private String firstImagePath(String path) {
		if (path == null || path.equals(""))
			return null;
		String[] paths = path.split(",");
		if (paths != null && paths.length != 0)
			return paths[0];
		return null;
	}
	
	private TStockAlarm findTStockAlarm(TCommodity tCommodity) {
		TStockAlarm tStockAlarm = new TStockAlarm();
		tStockAlarm.setTCommodity(tCommodity);
		tStockAlarm.setType("1");
		try {
			List<TStockAlarm> tStockAlarmList = tStockAlarmService.findService(tStockAlarm);
			if (tStockAlarmList != null && tStockAlarmList.size() != 0) {
				return tStockAlarmList.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private void Money() {
		String price = Price.getText().getText();
		if(price!=null&&!price.toString().equals("")&&MatcherFormatUtil.MatcherPriceScheme(price.toString())){
			switch(DiscountType.getBox().getSelectedIndex()) {
				case 0:
					DiscountPrice.getText().setText(price);
					return;
				case 1:
					String disCount = DisCount.getText().getText();
					if(disCount!=null&&!disCount.toString().equals("")&&MatcherFormatUtil.MatcherPriceScheme(disCount.toString())){
						DiscountPrice.getText().setText((double)Math.round(Double.parseDouble(price)*Double.parseDouble(disCount)*100)/100+"");
					}
					return;
				case 2:
					DiscountPrice.getText().setText("");
					return;
			}
		} else {
			DiscountPrice.getText().setText("");
		}
	}
	@Override
	public void caretUpdate(CaretEvent e) {
		Money();
	}
	
	public static void main(String[] args) {
		DataCommodityAddOrModifyDialog dialog = new DataCommodityAddOrModifyDialog(null, "", true);
		dialog.setVisible(true);
	}
}